package me.firstapp.manage.product;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.json.AbstractJsonObject;
import me.firstapp.common.json.PageObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.shop.JsonProduct;
import me.firstapp.common.module.shop.JsonProductInManage;
import me.firstapp.common.module.shop.JsonProductSkuRelation;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.manage.common.BaseManage;
import me.firstapp.manage.utils.BizData4Page;
import me.firstapp.spi.shop.ProductService;
import me.firstapp.spi.shop.ProductSkuRelService;

@Controller
@RequestMapping(value = "/productManage")
public class ProductManageAct extends BaseManage {

	@Autowired
	private ProductService productService;

	@Autowired
	private ProductSkuRelService productSkuRelService;

	@ResponseBody
	@RequestMapping(value = "/findProductPage.do", method = RequestMethod.POST)
	public void findProductPage(@RequestParam Map<String, Object> conditions, HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// 搜索条件
			Map<String, Object> searchParams = new HashMap<>();
			String sSearchJson = (String) conditions.get("sSearch");
			String startTime = null;
			String endTime = null;
			if (StrUtils.isNotNULL(sSearchJson)) {
				JSONObject jsonObject = JSONObject.parseObject(sSearchJson);
				if (jsonObject != null) {
					Set<String> keySet = jsonObject.keySet();
					for (String key : keySet) {
						if ("addTime".equals(key)) {
							// 日期范围判断
							String registerTimes = (String) jsonObject.get(key);
							if (registerTimes.contains(",")) {
								String[] registerTimesArra = registerTimes.split(",");
								startTime = registerTimesArra[0];
								endTime = registerTimesArra[1];
								if ("0".equals(startTime)) {
									startTime = null;
								}
								if ("0".equals(endTime)) {
									endTime = null;
								}
							}
						} else {
							searchParams.put(key, jsonObject.get(key));
						}
					}
				}
			}
			// 排序字段
			String mDataProp = "mDataProp_" + conditions.get("iSortCol_0");
			mDataProp = conditions.get(mDataProp).toString().replace("Str", "");
			// 排序方式
			String sSortDir_0 = (String) conditions.get("sSortDir_0");
			// 页容
			String iDisplayLengthStr = (String) conditions.get("iDisplayLength");
			// 是开始数不是当前页数...
			String iDisplayStartStr = (String) conditions.get("iDisplayStart");
			if (StrUtils.isNotNULL(iDisplayLengthStr) && StrUtils.isNotNULL(iDisplayStartStr)) {
				Integer iDisplayLength = Integer.valueOf(iDisplayLengthStr);
				Integer iDisplayStart = Integer.valueOf(iDisplayStartStr);
				// 当前页数
				Integer pageNo = iDisplayStart / iDisplayLength + 1;
				PageObject<JsonProductInManage> productPage = productService.findProductPage(pageNo, iDisplayLength,
						searchParams, mDataProp, sSortDir_0,
						StrUtils.isNULL(startTime) ? null : Long.valueOf(startTime),
						StrUtils.isNULL(endTime) ? null : Long.valueOf(endTime));
				SingleObject<Object> result = new SingleObject<Object>();
				BizData4Page<JsonProductInManage> bizData4Page = new BizData4Page<JsonProductInManage>();
				bizData4Page.setUserdata(conditions);
				if (productPage.getPage() != null) {
					bizData4Page.setPage(productPage.getPage().getPageNo());
					bizData4Page.setPagesize(productPage.getPage().getPageSize());
					bizData4Page.setRecords(productPage.getPage().getTotalCount());
					bizData4Page.setRows(new ArrayList<JsonProductInManage>(productPage.getPage().getList()));
					bizData4Page.setTotal(productPage.getPage().getTotalCount());
				}

				result.setCode(productPage.getCode());
				result.setMsg(productPage.getMsg());
				result.setObject(bizData4Page);
				ResponseUtils.renderJson(response, result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			AbstractJsonObject abstractJsonObject = new AbstractJsonObject();
			abstractJsonObject.setCode("error");
			abstractJsonObject.setMsg("发生未知错误");
			ResponseUtils.renderJson(response, abstractJsonObject);
		}
	}

	@RequestMapping(value = "/addProduct.do", method = RequestMethod.POST)
	public void addProduct(Long categoryId, String listImage, String smallImage, String images, String name,
			String summary, String detail, String deliver, Double deliverFee, Integer sort, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<JsonProduct> result = productService.addProduct(categoryId, listImage, smallImage, images, name,
				summary, detail, deliver, deliverFee, sort);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/updateProduct.do", method = RequestMethod.POST)
	public void updateProduct(Long productId, Long categoryId, String listImage, String smallImage, String images,
			String name, String summary, String detail, String deliver, Double deliverFee, Integer sort,
			Integer disable, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<JsonProduct> result = productService.updateProduct(productId, categoryId, listImage, smallImage,
				images, name, summary, detail, deliver, deliverFee, sort, disable);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/deleteProduct.do", method = RequestMethod.POST)
	public void deleteProduct(String ids, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> result = productService.deleteProducts(ids);
		ResponseUtils.renderJson(response, result);
	}

	@ResponseBody
	@RequestMapping(value = "/findProductSkuRel.do", method = RequestMethod.POST)
	public void findProductSkuRelPage(@RequestParam Map<String, Object> conditions, Long productId,
			HttpServletRequest request, HttpServletResponse response) {

		try {
			// 搜索条件
			Map<String, Object> searchParams = new HashMap<>();
			String sSearchJson = (String) conditions.get("sSearch");
			if (StrUtils.isNotNULL(sSearchJson)) {
				JSONObject jsonObject = JSONObject.parseObject(sSearchJson);
				if (jsonObject != null) {
					Set<String> keySet = jsonObject.keySet();
					for (String key : keySet) {
						searchParams.put(key, jsonObject.get(key));
					}
				}
			}
			searchParams.put("productId", productId);
			// 排序字段
			String mDataProp = "mDataProp_" + conditions.get("iSortCol_0");
			mDataProp = conditions.get(mDataProp).toString().replace("Str", "");
			// 排序方式
			String sSortDir_0 = (String) conditions.get("sSortDir_0");
			// 页容
			String iDisplayLengthStr = (String) conditions.get("iDisplayLength");
			// 是开始数不是当前页数...
			String iDisplayStartStr = (String) conditions.get("iDisplayStart");
			if (StrUtils.isNotNULL(iDisplayLengthStr) && StrUtils.isNotNULL(iDisplayStartStr)) {
				Integer iDisplayLength = Integer.valueOf(iDisplayLengthStr);
				Integer iDisplayStart = Integer.valueOf(iDisplayStartStr);
				// 当前页数
				Integer pageNo = iDisplayStart / iDisplayLength + 1;
				PageObject<JsonProductSkuRelation> skuPage = productSkuRelService
						.findApiJsonProductSkuRelationPage(pageNo, iDisplayLength, searchParams, mDataProp, sSortDir_0);
				SingleObject<Object> result = new SingleObject<Object>();
				BizData4Page<JsonProductSkuRelation> bizData4Page = new BizData4Page<JsonProductSkuRelation>();
				bizData4Page.setUserdata(conditions);
				if (skuPage.getPage() != null) {
					bizData4Page.setPage(skuPage.getPage().getPageNo());
					bizData4Page.setPagesize(skuPage.getPage().getPageSize());
					bizData4Page.setRecords(skuPage.getPage().getTotalCount());
					bizData4Page.setRows(new ArrayList<JsonProductSkuRelation>(skuPage.getPage().getList()));
					bizData4Page.setTotal(skuPage.getPage().getTotalCount());
				}

				result.setCode(skuPage.getCode());
				result.setMsg(skuPage.getMsg());
				result.setObject(bizData4Page);
				ResponseUtils.renderJson(response, result);
			}
		} catch (Exception e) {
			e.printStackTrace();
			AbstractJsonObject abstractJsonObject = new AbstractJsonObject();
			abstractJsonObject.setCode("error");
			abstractJsonObject.setMsg("发生未知错误");
			ResponseUtils.renderJson(response, abstractJsonObject);
		}
	}

	@RequestMapping(value = "/addProductSkuRelation.do", method = RequestMethod.POST)
	public void addProductSkuRelation(Long productId, String skuName1, String skuValue1, String skuName2,
			String skuValue2, Integer stock, Double price, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<JsonProductSkuRelation> result = productSkuRelService.addProductSkuRelation(productId, skuName1,
				skuValue1, skuName2, skuValue2, stock, price);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/updateProductSkuRelation.do", method = RequestMethod.POST)
	public void updateProductSkuRelation(Long productSkuRelationId, String skuName1, String skuValue1, String skuName2,
			String skuValue2, Integer stock, Double price, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<JsonProductSkuRelation> result = productSkuRelService
				.updateProductSkuRelation(productSkuRelationId, skuName1, skuValue1, skuName2, skuValue2, stock, price);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/deleteProductSkuRel.do", method = RequestMethod.POST)
	public void deleteProductSkuRel(String ids, HttpServletRequest request, HttpServletResponse response) {
		SingleObject<Object> result = productSkuRelService.deleteProductSkuRelations(ids);
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping(value = "/setDefaultProductSkuRel.do", method = RequestMethod.POST)
	public void setDefaultProductSkuRel(Long productSkuRelationId, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<JsonProductSkuRelation> result = productSkuRelService
				.setDefaultProductSkuRelation(productSkuRelationId);
		ResponseUtils.renderJson(response, result);
	}
}
